package com.genITeam.ria.bl;

import com.genITeam.ria.dao.TheadPostDAO;
import com.genITeam.ria.dao.ViewForumDAO;
import com.genITeam.ria.exception.NGFException;
import com.genITeam.ria.utility.HibernateUtils;
import com.genITeam.ria.vo.Member;
import com.genITeam.ria.vo.Posts;
import java.util.*;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class ViewForumBL {

	public ViewForumBL() {
		BasicConfigurator.configure();
	}

	Logger logger = Logger.getLogger(ViewForumBL.class);

	/**
	 * getRootNode Return the Root Node of the Three
	 * 
	 * @param none
	 * 
	 * @return none
	 * @throws NGFException
	 */

	public void getRootNode() throws NGFException {
		BasicConfigurator.configure();
		ViewForumDAO viewForumDAO = new ViewForumDAO();
		Session session = null;
		Transaction tx = null;
		try {
			logger.info("Start getRootNode");
			session = HibernateUtils.getSessionFactory().getCurrentSession();
			tx = session.getTransaction();
			tx.begin();

			Posts threadPostVo = viewForumDAO.getRootNode(session);

			logger.info("Root Node : ");
			logger.info("Id = " + threadPostVo.getPostId());
			logger.info("Parent Id = " + threadPostVo.getPosts().getPostId());
			logger.info("Title = " + threadPostVo.getTitle());
			logger.info("Description = " + threadPostVo.getMessage());
			tx.commit();
		} catch (Exception e) {
			if (tx != null && tx.isActive()) {
				tx.rollback();
			}
			logger.error("Exception = " + e.toString());
			throw new NGFException(e.getMessage());
		} finally {
			session.close();
		}
	}

	/**
	 * getChildNodes Brings the children nodes of the parent node specified as
	 * parameter
	 * 
	 * @param int
	 * 
	 * @return none
	 * @throws NGFException
	 */

	public void getChildNodes(int parentNode) throws NGFException {
		ViewForumDAO viewForumDAO = new ViewForumDAO();
		BasicConfigurator.configure();
		Session session = null;
		Transaction tx = null;
		try {
			logger.info("Start getChildNodes");
			session = HibernateUtils.getSessionFactory().getCurrentSession();
			tx = session.getTransaction();
			tx.begin();
			ArrayList children = viewForumDAO
					.getChildNodes(parentNode, session);
			Posts threadPostVo = new Posts();
			logger.info(children.size() + "");
			for (int i = 0; i < children.size(); i++) {
				threadPostVo = (Posts) children.get(i);
				logger.info(threadPostVo.getPostId() + "");
				logger.info(threadPostVo.getTitle());
				logger.info(threadPostVo.getPosts().getPostId() + "");
				logger.info(threadPostVo.getMessage());
			}
		} catch (Exception e) {
			if (tx != null && tx.isActive()) {
				tx.rollback();
			}
			logger.error("Exception = " + e.toString());
			throw new NGFException(e.getMessage());
		} finally {
			session.close();
		}

	}

	/**
	 * performDFS Performs the process of DFS. It is necessary to perform DFS
	 * operation in order to generate correct xml forum tree
	 * 
	 * @param int
	 * 
	 * @return ArrayList
	 * @throws NGFException
	 */

	public ArrayList performDFS() throws NGFException {
		// System.out.println("in BO - TreeCodeGeneratorBean -> performDFS()");
		BasicConfigurator.configure();
		ViewForumDAO viewForumDAO = new ViewForumDAO();
		ArrayList dfs = new ArrayList();
		Session session = null;
		Transaction tx = null;

		try {
			logger.info("Start performDFS");
			session = HibernateUtils.getSessionFactory().getCurrentSession();
			tx = session.getTransaction();
			tx.begin();

			Posts threadPostVo = viewForumDAO.getRootNode(session);

			int cnt = viewForumDAO.getTotalCount(session);
			dfs.add(0, threadPostVo);
			int iPlusjValue = 1;
			for (int i = 0; i < cnt; i++) {
				iPlusjValue = i;
				ArrayList test = viewForumDAO.getChildNodes(
						((Posts) dfs.get(i)).getPostId(), session);
				boolean t = ((Posts) dfs.get(i)).getTitle().startsWith("/");
				if (t == false) {
					for (int j = 0; j < test.size(); j++) {
						dfs.add(i + j + 1, ((Posts) test.get(j)));
						iPlusjValue = i + j + 1;
					}
					Posts d = new Posts();
					// d.setId(((ForumVo)dfs.get(i)).getId());
					// d.setId("/node");
					d.setTitle("/" + ((Posts) dfs.get(i)).getId());
					// d.setParentID();
					dfs.add(iPlusjValue + 1, d);
				} else {
					cnt++;
				}
			}
			// --------------------------------------------
			System.out.println("................");
			System.out.println(dfs.size());
			System.out.println("................");

			for (int j = 0; j < dfs.size(); j++) {
				Posts dto = (Posts) dfs.get(j);
				logger.info("<");
				logger.info(dto.getId() + "");
				logger.info(">");
				logger.info(dto.getTitle());

			}
			tx.commit();
		} catch (Exception e) {
			System.out.println(e.getMessage());
			if (tx != null && tx.isActive()) {
				tx.rollback();
			}
			logger.error("Exception = " + e.toString());
			throw new NGFException(e.getMessage());
		} finally {
			session.close();
		}

		return dfs;

	}

	/**
	 * performDFS Saves the xml forum tree into file. However, here we are
	 * returning a String that contains the whole xml tree generated
	 * 
	 * @param none
	 * 
	 * @return String
	 * @throws NGFException
	 */

	public String saveToXmlFile() throws NGFException {
		BasicConfigurator.configure();
		ArrayList xmlFileData = performDFS();
		int postId;
		String title;
		String isLeaf;
		String description;
		int pid;
		String line = "";
		try {
			logger.info("Start saveToXmlFile");
			for (int i = 0; i < xmlFileData.size(); i++) {
				postId = ((Posts) xmlFileData.get(i)).getPostId();
				title = ((Posts) xmlFileData.get(i)).getTitle();
				pid = ((Posts) xmlFileData.get(i)).getPosts().getPostId();
				isLeaf = ((Posts) xmlFileData.get(i)).getIsLeaf();
				description = ((Posts) xmlFileData.get(i)).getMessage();

				if (((Posts) xmlFileData.get(i)).getTitle().startsWith("/")) {
					line += "</node>";

				} else {
					line += "<node postId=\"" + postId + "\"  title=\"" + title
							+ "\"  parentId=\"" + pid + "\"  isLeaf=\""
							+ isLeaf + "\"  description=\"" + description
							+ "\">";

				}
				// printWriter.println(line);
			}
			logger.info(line);
			System.out.println(line);
			/*
			 * printWriter.flush(); printWriter.close(); fileWriter.close();
			 */
		} catch (Exception e) {
			logger.error("Exception = " + e.toString());
			throw new NGFException(e.getMessage());
		}
		return line;

	}

	/**
	 * getPost
	 * 
	 * @param none
	 * 
	 * @return String
	 * @throws NGFException
	 */

	public String getPost(String post_id) throws NGFException {
		Transaction tx = null;
		try {
			logger.info("Start getPost");
			TheadPostDAO postDAO = new TheadPostDAO();

			Session session = HibernateUtils.getSessionFactory()
					.getCurrentSession();
			tx = session.getTransaction();
			tx.begin();
			Posts post = postDAO.getForums(Integer.parseInt(post_id), session);

			StringBuffer xml = new StringBuffer("");
			this.generatePostsxmlRecursive(post, xml);

			System.out.print("xml = " + xml.toString());
			tx.commit();
			return xml.toString();

		} catch (Exception e) {
			if (tx != null && tx.isActive()) {
				tx.rollback();
			}
			logger.error("Exception = " + e.toString());
			throw new NGFException(e.getMessage());

		}
	}

	/**
	 * generatePostsxmlRecursive
	 * 
	 * @param Posts,
	 *            StringBuffer
	 * 
	 * @return none
	 * @throws NGFException
	 */

	public void generatePostsxmlRecursive(Posts post, StringBuffer xml)
			throws NGFException {

		try {
			logger.info("Start generatePostsxmlRecursive");
			xml.append("<node postId=\"" + post.getPostId() + "\" ");
			xml.append(" title=\"" + post.getTitle() + "\" ");
			xml.append(" message=\"" + post.getMessage() + "\" ");
			xml.append(" postDate=\"" + post.getPostDate() + "\"");
			xml.append(" memberId=\"" + post.getMember().getNick() + "\"");

			if (post.getPosts() != null)
				xml.append(" parentId=\"" + post.getPosts().getPostId() + "\"");
			else
				xml.append(" parentId=\"" + 0 + "\"");

			xml.append(" postType=\"" + post.getPostType() + "\"");
			xml.append(" noOfView=\"" + post.getNoOfView() + "\"");
			xml.append(" isLeaf=\"" + post.getIsLeaf() + "\"");
			xml.append(" filePath=\"" + post.getFilePath() + "\"");
			xml.append(" >\n");

			Iterator i = post.getPostses().iterator();
			Posts p = null;
			while (i.hasNext()) {
				p = (Posts) i.next();
				if (p.getPostType() == 'F')
					generatePostsxmlRecursive(p, xml);
			}// end for

			xml.append("</node>");
			System.out.println(xml.toString());
		} catch (Exception e) {
			logger.error("Exception = " + e.toString());
			throw new NGFException(e.getMessage());
		}
	}

	/**
	 * updateForumData Use to Update Forum Title and Description
	 * 
	 * @param Posts,
	 *            StringBuffer
	 * 
	 * @return none
	 * @throws NGFException
	 */

	public void updateForumData(Posts postsVo) throws NGFException {
		Session session = null;
		Transaction tx = null;
		try {
			logger.info("Start updateForumData");
			session = HibernateUtils.getSessionFactory().getCurrentSession();
			tx = session.getTransaction();
			tx.begin();
			ViewForumDAO viewForumDAO = new ViewForumDAO();
			viewForumDAO.updateForumData(postsVo, session);
			tx.commit();

		} catch (Exception e) {
			if (tx != null && tx.isActive()) {
				tx.rollback();
			}
			logger.error("Exception = " + e.toString());
			throw new NGFException(e.getMessage());

		}

	}

	/**
	 * addForumData Use to Add New Forum
	 * 
	 * @param Posts,
	 *            StringBuffer
	 * 
	 * @return none
	 * @throws NGFException
	 */

	public void addForumData(Posts postsVo) throws NGFException {
		Session session = null;
		Transaction tx = null;
		try {
			logger.info("Start addForumData");
			session = HibernateUtils.getSessionFactory().getCurrentSession();
			tx = session.getTransaction();
			tx.begin();
			ViewForumDAO viewForumDAO = new ViewForumDAO();
			viewForumDAO.addForumData(postsVo, session);
			tx.commit();

		} catch (Exception e) {
			if (tx != null && tx.isActive()) {
				tx.rollback();
			}
			logger.error("Exception = " + e.toString());
			throw new NGFException(e.getMessage());

		}

	}

	/**
	 * getForumById Return the Forum Detail by Id
	 * 
	 * @param Posts
	 * 
	 * @return Posts
	 * @throws NGFException
	 */

	public Posts getForumById(Posts postsVo) throws NGFException {
		System.out.println("getForumById");
		Session session = null;
		Transaction tx = null;
		Posts posts = new Posts();
		try {
			logger.info("Start getForumById");
			ViewForumDAO viewForumDAO = new ViewForumDAO();
			session = HibernateUtils.getSessionFactory().getCurrentSession();
			tx = session.getTransaction();
			tx.begin();
			posts = viewForumDAO.getForumById(postsVo, session);
			tx.commit();
		} catch (Exception e) {
			if (tx != null && tx.isActive()) {
				tx.rollback();
			}
			logger.error("Exception = " + e.toString());
			throw new NGFException(e.getMessage());
		}
		return posts;
	}

	public static void main(String[] args) throws NGFException {
		ViewForumBL viewForumBL = new ViewForumBL();
		Posts pVo = new Posts();
		Member member = new Member();
		// System.out.println("hello wrold");
		member.setId(1);
		pVo.setPostId(307);
		pVo.setIsLeaf("true");
		pVo.setTitle("DSSD ");
		pVo.setMessage("DSSD is a great course; i love it");
		pVo.setPostDate(new Date());
		pVo.setMember(member);
		// pVo.setPosts(new Posts().setPostId(8));
		Posts p = new Posts();
		p.setPostId(306);
		// int pid = p.getPostId();
		pVo.setPosts(p);
		pVo.setPostType('F');
		pVo.setNoOfView(0);

		viewForumBL.updateForumData(pVo);

		/*
		 * try { viewForumBL.getPost("1"); } catch (Exception e) { throw new
		 * NGFException(e.getMessage()); }
		 */

	}
}
